import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/vacant_state.dart';
import 'package:vista/features/message/viewmodels/friends_list_viewmodel.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/services/relation_bond.dart';

/// 朋友列表视图
/// 显示所有朋友列表，支持取消关注和发起聊天
class FriendsListView extends StatelessWidget {
  const FriendsListView({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<FriendsListViewModel>.reactive(
      viewModelBuilder:
          () => FriendsListViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<RelationBond>(),
            getIt.get<DialogLens>(),
          )..initialize(),
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/my-background.png'),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              bottom: false,
              child:
                  viewModel.isBusy
                      ? const Center(child: CircularProgressIndicator())
                      : viewModel.currentUser == null
                      ? _buildLoginPrompt(context)
                      : _buildContent(context, viewModel),
            ),
          ),
        );
      },
    );
  }

  /// 构建登录提示
  Widget _buildLoginPrompt(BuildContext context) {
    return [
          VacantState(
            message: 'Please login to view friends',
            imagePath: 'assets/images/empty1.png',
          ),
          SizedBox(height: 32.h),
          ElevatedButton(
            onPressed: () {
              getIt<NavigationService>().navigateTo(Routes.login);
            },
            style: ElevatedButton.styleFrom(
              padding: EdgeInsets.symmetric(horizontal: 48.w, vertical: 16.h),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12.r),
              ),
              backgroundColor: ColorConstants.accentColor,
              foregroundColor: Colors.white,
              elevation: 0,
            ),
            child: Text(
              'Login',
              style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
            ),
          ),
        ]
        .verticalShot(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
        )
        .frameHorizontal(24.w);
  }

  /// 构建内容
  Widget _buildContent(BuildContext context, FriendsListViewModel viewModel) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 顶部标题栏
        Padding(
          padding: EdgeInsets.fromLTRB(14.w, 0.h, 14.w, 14.w),
          child: Row(
            children: [
              // 返回按钮
              GestureDetector(
                onTap: () => Navigator.of(context).pop(),
                child: Icon(
                  Icons.chevron_left,
                  size: 28.w,
                  color: Colors.black87,
                ),
              ),

              // 标题
              Expanded(
                child: Center(
                  child: Text(
                    'My Friend',
                    style: TextStyle(
                      fontSize: 20.sp,
                      fontFamily:
                          GoogleFonts.alegreyaSans(
                            fontWeight: FontWeight.w800,
                          ).fontFamily,
                      color: Colors.black87,
                    ),
                  ),
                ),
              ),
              SizedBox(width: 32.w),
            ],
          ),
        ),
        // 朋友列表
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white.withValues(alpha: 0.40),
              borderRadius: BorderRadius.circular(16.r),
            ),
            child:
                viewModel.friends.isEmpty
                    ? Center(
                      child: VacantState(
                        message: 'No friends yet',
                        imagePath: 'assets/images/empty1.png',
                      ),
                    )
                    : SingleChildScrollView(
                      padding: EdgeInsets.all(14.w),
                      child: [
                        for (int i = 0; i < viewModel.friends.length; i++) ...[
                          _buildFriendItem(
                            context,
                            viewModel,
                            viewModel.friends[i],
                          ),
                          if (i < viewModel.friends.length - 1)
                            SizedBox(height: 14.w),
                        ],
                        SizedBox(height: 80.h), // 底部留白，防止被导航栏遮住
                      ].verticalShot(
                        crossAxisAlignment: CrossAxisAlignment.start,
                      ),
                    ),
          ).frameHorizontal(14.w),
        ),
      ],
    );
  }

  /// 构建朋友项
  Widget _buildFriendItem(
    BuildContext context,
    FriendsListViewModel viewModel,
    friend,
  ) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8.r),
        border: Border.all(color: Colors.black, width: 1.w),
      ),
      padding: EdgeInsets.all(8.w),
      child: Row(
        children: [
          // 头像
          GestureDetector(
            onTap: () async {
              // 检查是否是当前用户
              final currentUser = await getIt<AuthFocus>().getCurrentUser();
              if (currentUser != null && currentUser.id == friend.id) {
                return; // 是自己的头像，不跳转
              }
              // 跳转到他人主页
              if (context.mounted) {
                await Navigator.of(context).pushNamed(
                  Routes.otherProfile,
                  arguments: {'userId': friend.id},
                );
              }
            },
            child: CircleAvatar(
              radius: 30.r,
              backgroundColor: Colors.grey[200],
              backgroundImage:
                  friend.avatar != null ? AssetImage(friend.avatar!) : null,
              child:
                  friend.avatar == null
                      ? Icon(Icons.person, size: 28.w, color: Colors.grey)
                      : null,
            ),
          ),
          SizedBox(width: 14.w),
          // 名字和用户名
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  friend.username,
                  style: TextStyle(
                    fontSize: 20.sp,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w800,
                        ).fontFamily,
                    color: Colors.black87,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  friend.signature ?? '',
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontFamily:
                        GoogleFonts.alegreyaSans(
                          fontWeight: FontWeight.w800,
                        ).fontFamily,
                    color: Colors.grey[600],
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ],
            ),
          ),
          // 操作按钮
          Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 删除按钮
              GestureDetector(
                onTap: () async {
                  final confirmed = await showDialog<bool>(
                    context: context,
                    builder:
                        (context) =>
                            _buildUnfollowDialog(context, friend.username),
                  );
                  if (confirmed == true) {
                    await viewModel.unfollowFriend(friend.id);
                  }
                },
                child: Container(
                  width: 20.w,
                  height: 20.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: Colors.grey[200],
                    border: Border.all(color: Colors.black, width: 1),
                  ),
                  padding: EdgeInsets.all(2.w),
                  child: Image.asset(
                    'assets/images/delete.png',
                    fit: BoxFit.contain,
                  ),
                ),
              ),
              SizedBox(height: 8.h),
              // 聊天按钮
              GestureDetector(
                onTap: () async {
                  final hasChat = await viewModel.hasChatWithUser(friend.id);
                  if (!hasChat) {
                    await viewModel.createChatWithUser(friend.id);
                  }
                  // 跳转到聊天页面
                  if (context.mounted) {
                    Navigator.of(context).pushNamed(
                      Routes.chat,
                      arguments: {'otherUserId': friend.id},
                    );
                  }
                },
                child: Container(
                  width: 20.w,
                  height: 20.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    color: ColorConstants.accentColor,
                    border: Border.all(color: Colors.black, width: 1),
                  ),
                  padding: EdgeInsets.all(2.w),
                  child: Image.asset(
                    'assets/images/chat.png',
                    fit: BoxFit.contain,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建取消关注确认对话框
  Widget _buildUnfollowDialog(BuildContext context, String username) {
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24.r)),
      insetPadding: EdgeInsets.symmetric(horizontal: 40.w, vertical: 80.h),
      elevation: 0,
      backgroundColor: Colors.transparent,
      child: Container(
        constraints: BoxConstraints(maxWidth: 320.w, minWidth: 280.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(24.r),
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [const Color(0xFFFFA680), const Color(0xFFFFEBE6)],
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 20.w,
              offset: Offset(0, 10.h),
            ),
          ],
        ),
        child: [
              // 标题
              Text(
                'Unfollow',
                style: TextStyle(
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w800,
                  fontFamily:
                      GoogleFonts.alegreyaSans(
                        fontWeight: FontWeight.w800,
                      ).fontFamily,
                  color: Colors.black87,
                ),
              ),
              SizedBox(height: 16.h),
              // 描述
              Text(
                'Are you sure you want to unfollow $username?',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.black.withOpacity(0.7),
                  height: 1.5,
                ),
                textAlign: TextAlign.center,
              ),
              SizedBox(height: 36.h),
              // 按钮组
              [
                    // 取消按钮
                    Expanded(
                      child: OutlinedButton(
                        onPressed: () => Navigator.of(context).pop(false),
                        style: OutlinedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 16.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          side: BorderSide(
                            color: Colors.black.withOpacity(0.2),
                            width: 1.5,
                          ),
                        ),
                        child: Text(
                          'Cancel',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                            color: Colors.black87,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 14.w),
                    // 确认按钮
                    Expanded(
                      child: ElevatedButton(
                        onPressed: () => Navigator.of(context).pop(true),
                        style: ElevatedButton.styleFrom(
                          padding: EdgeInsets.symmetric(vertical: 16.h),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          backgroundColor: Colors.black87,
                          foregroundColor: Colors.white,
                          elevation: 0,
                        ),
                        child: Text(
                          'Unfollow',
                          style: TextStyle(
                            fontSize: 16.sp,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ),
                  ]
                  .horizontalGallery(
                    mainAxisAlignment: MainAxisAlignment.center,
                  )
                  .frameHorizontal(0),
            ]
            .verticalShot(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
            )
            .frameAll(36.w),
      ),
    );
  }
}
